4

I have a txt file. In that file, I want to filter a particular word.

Example:

$PILOT_FIRSTNAME $PILOT_LASTNAME. This is the final confirmation for this flight.

I want output like:

PILOT_FIRSTNAME

PILOT_LASTNAME

What are all the words with $, that word only fetch?

5

Using grep's PCRE (perl-compatible regular expression) mode:

$ grep -Po '\$\K\w*' yourfile
PILOT_FIRSTNAME
PILOT_LASTNAME
  • \$ : match literal $
  • \K : (ignore it)
  • \w : followed by zero or more word characters

If you want to match and keep the literal $ character, then you don't need the \K modifier - and in fact you don't need PCRE at all, you can simply use

$ grep -o '\$\w*' yourfile
$PILOT_FIRSTNAME
$PILOT_LASTNAME

or (perhaps more portably)

grep -o '\$[_[:alnum:]]*' yourfile
$PILOT_FIRSTNAME
$PILOT_LASTNAME
3
  • If i want with $ symobol($PILOT_FIRSTNAME) means.. Wat i do
    – hikoo
    Aug 23 '16 at 13:48
  • 1
    @hikoo sorry I don't understand your question. Are you asking how to evaluate variables $PILOT_FIRSTNAME and $PILOT_LASTNAME? If so please edit your question to make it clear what you really want - preferably with a minimal, working example. Aug 23 '16 at 13:56
  • @steeldriver I think he wants the same regexp without the \K
    – oals
    Aug 23 '16 at 15:41
5

So if you want to print fields of the file as newline separated if starts with $, you can do:

awk '{for(i=1;i<=NF;i++){if($i~/^\$/){printf "%s\n",substr($i,2)}}}' file.txt

Expanded form:

awk '{
    for (i=1;i<=NF;i++)
        { if($i~/^\$/)
                { printf "%s\n",substr($i,2) }
        }
     }' file.txt

Here we are iterating over the fields (for (i=1;i<=NF;i++)), if the field starts with $ (if($i~/^\$/)), then printing it with a trailing newline starting from second character (printf "%s\n",substr($i,2)).


On the other hand, if the number of fields is fixed and not many, then sed is also a viable option, here assuming two fields:

sed -nr 's/^\$([^[:blank:]]+)[[:blank:]]+\$([^[:blank:]]+)$/\1\n\2/p' file.txt

Matching $ at the start of each whitespace separated field, capturing the field (([^[:blank:]]+)), then in the replacement set the fields as newline separated (1\n\2).


Example:

$ cat file.txt
$PILOT_FIRSTNAME $PILOT_LASTNAME
$FOO $BAR
PILOT_FOO PILOT_BAR

$ awk '{for(i=1;i<=NF;i++){if($i~/^\$/){printf "%s\n",substr($i,2)}}}' file.txt
PILOT_FIRSTNAME
PILOT_LASTNAME
FOO
BAR

$ sed -nr 's/^\$([^[:blank:]]+)[[:blank:]]+\$([^[:blank:]]+)$/\1\n\2/p' file.txt
PILOT_FIRSTNAME
PILOT_LASTNAME
FOO
BAR

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.