0

I have a file that looks like this:

-config1
-config2 param2
-config3 param3a param3b
-config4 param4

and I can use the following to extract param2:

echo $(<file) | cut -d' ' -f3

However I would like to fix it such that I always get the word after -config2, such that if these get re-arranged or something is inserted, my command will still work. What should I be looking at?

Clarification: there may be more than one params on any given line (or none at all), however there will always be at most one -config option per line.

  • 1
    The answers posted so far make different assumptions about what can vary in the layout of your input file. Can you clarify? Do we know that -config2 is followed by a single word on its line? Can there be multiple -configX options on the same line? – dhag Mar 31 '15 at 19:34
  • @dhag right now they are only -config param or simple -config (which toggles a flag), but I suppose there could be -config1 param1a param2b at some point in the future - I was using echo to convert the lines into a single one with spaces, but that's more of a work-around than a feature. There shouldn't be more than 1 '-' on any line however. – user2813274 Mar 31 '15 at 19:40
  • Oh, OK. Then I misunderstood what you meant when I edited your post. I'll revert that bit. Shouldn't it be cut -f4, to select param2, in that case? I will also update my answer to correspond to this new piece of information. – dhag Mar 31 '15 at 19:44
2

I would use awk for this

awk '/^-config2/ {print $2}' file

It print the second argument of lines starting with -config2. The ^ means the beginning of the line.

| improve this answer | |
2

Try this:

perl -ne 'if (/-config2\s*(.*)/) { print "$1\n"; }'

This looks for lines matching -config2, and then prints the rest of the line (\s* matches an arbitrary amount of white space, (.*) matches anything and binds it to $1).

My previous answer, which assumed that -config2 was followed by a single word:

perl -ne 'if (/-config2\s*(\S+)/) { print "$1\n"; }'

This looks for lines matching -config2, and then prints the first token after it (\s* matches an arbitrary amount of white space, (\S+) matches a non-empty sequence of non-whitespace characters and binds it to $1).

| improve this answer | |
1

A variation with sed:

sed -n 's/^-config2 //p' file

-n suppress automatic printing

s/^-config2 // substitute -config2 and trailing space on line start with nothing in pattern space

p print pattern space

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.