1

I have string lists:

./index.blade.php core/resources/views/admin/pages/setting/index.blade.php
./country-flag vendor/country-flag

I want to fetch only string after space, how should i write it in sed or awk?

I tried this but it didn't work

echo "./country-flag vendor/country-flag"  | awk '/^[[blank]]/{p=1}p'

Expected output:

vendor/country-flag
oguz ismail
  • 1
  • 16
  • 47
  • 69

4 Answers4

3

By default the field seperator in awk is space, so we can refer the second field after the space with the help of $2

echo "./country-flag vendor/country-flag"  |  awk '{print $2}'

vendor/country-flag
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
0

I want to explain why

echo "./country-flag vendor/country-flag"  | awk '/^[[blank]]/{p=1}p'

failed to yield desired result. Firstly bracket expressions in awk have form of [:name:] so it should be [[:blank:]] not [[blank]]. Secondly after changing your awk code to /^[[:blank:]]/{p=1}p it will be testing if line starts with blank (space or tab). If so set p to 1. As printing of line depends on value of p it will print first line starting with space or tab and all following lines, as p value is never changed to anything but 1.

Daweo
  • 31,313
  • 3
  • 12
  • 25
0

You can do:

$ echo "./country-flag vendor/country-flag"  | awk '/[[:blank:]]/{print $2}'
vendor/country-flag

More typical in awk (since it, by default splits on [[:space:]] already) is to use the NF variable that denotes the number of fields in the current record:

$ echo "./country-flag vendor/country-flag"  | awk 'NF>1{print $2}'
vendor/country-flag

With sed you just delete the first field:

echo "./country-flag vendor/country-flag"  | sed -E 's/^[^[:space:]]*[[:space:]]*//'

If you want to print a line with no spaces unmodified but only after the first space if there is one:

echo "./country-flag vendor/country-flag
./country-flagvendor/country-flag"  |
sed -E '/^[^[:space:]]*$/n; s/^[^[:space:]]*[[:space:]]*//'

Prints:

vendor/country-flag
./country-flagvendor/country-flag
dawg
  • 98,345
  • 23
  • 131
  • 206
0

As suggested by Vishal Singh, this sed solution is most terse

echo "./country-flag vendor/country-flag" | sed 's/.* //'
vendor/country-flag

You could also use grep

echo "./country-flag vendor/country-flag" | grep -Po '\b[^ ]+$'
vendor/country-flag

The grep options say: using perl -P print the matching part only o

The regular expression says: after word boundary \b match anything that isn't space [^ ] one or more times + before the end of the line $

Kleber Noel
  • 303
  • 3
  • 9