-2

we can easily to capture the first field by awk as this syntax

 capture=` echo 1 2 3 | awk '{print $1}' `

we can easily to capture the sec field by awk as this syntax , and so on

 capture=` echo 1 2 3 | awk '{print $2}' `

but I prefer to avoid to use echo just to capture the requested field

what is the same results with bash ?

my goal is to do it more simple and if we can not use echo - then its better

10
  • 1
    What are you actually trying to do? Why not just write your script in Awk? Awk is a programming language, not just for one-liners.
    – Wildcard
    Commented Jan 18, 2018 at 9:04
  • I just not want to use echo , we are not talking here about awk , awk is just fine , but want to avoid using echo , ot any other approach with echo
    – jango
    Commented Jan 18, 2018 at 9:11
  • so hope that my question now is more clearly if not please ask any want to put on the table and I will promise I will answer on any question , but I just not understand why I got (-2) what is wrong with my question ?
    – jango
    Commented Jan 18, 2018 at 9:19
  • 2
    @jango, if you care about speed / resource use, to the level that a shell builtin command matters, stop using the shell. It's measurable slower than, say, awk or Perl, even for the tasks that can be done just in the shell, without forking off other processes.
    – ilkkachu
    Commented Jan 18, 2018 at 9:37
  • 3
    Your first example can be replaced by capture=1, the second by capture=2. You see the problem? We need to know what the source of the data is to give the matching answer. Of course it's useless to echo a string just to modify it. So what do you really want to do?
    – Philippos
    Commented Jan 18, 2018 at 10:21

1 Answer 1

2

Leaving aside whether the shell is the suitable tool here for a moment, you could replace it with a herestring as you say you’re using bash.

capture=$( awk ‘{ print $1 }’ <<< “1 2 3” )

More info https://unix.stackexchange.com/a/80372

4
  • 1
    this is not significantly different to just using echo.
    – cas
    Commented Jan 18, 2018 at 10:18
  • @cas it avoids creating more sub shells, I think.
    – Guy
    Commented Jan 18, 2018 at 10:26
  • Doesn't it create temp files, though? I seem to recall reading that that's how here strings are implemented in most shells.
    – Wildcard
    Commented Jan 18, 2018 at 14:13
  • @Wildcard after a bit of searching you seem to be right, for bash at least. I didn’t look for others tho.
    – Guy
    Commented Jan 18, 2018 at 16:55

Not the answer you're looking for? Browse other questions tagged .