Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

How to set "||" as your field separator in awk

 
Wang,MinJie
Super Advisor

How to set "||" as your field separator in awk

Hi all

I've created a file called test.txt and the content of it is as the following:

aaa||bbb

Then I run
#awk -F "||" '{print $1}' test.txt

and it output "aaa||bbb"

So I think it seems like "||" doesn't work

How can I use "||" as field separator?

Tks in advance
5 REPLIES 5
Oviwan
Honored Contributor

Re: How to set "||" as your field separator in awk

hey

use it like this:
awk -F "[||]" '{print $1}' test.txt

source:
http://www.gnu.org/manual/gawk/html_node/Command-Line-Field-Separator.html

Regards
Dennis Handly
Acclaimed Contributor

Re: How to set "||" as your field separator in awk

You need to use either of these:
$ echo "hi||guy||sam" | awk -F"[|][|]" '{print $1, $3}'
hi sam
$ echo "hi||guy||sam" | awk -F"\\\|\\\|" '{print $1, $3}'
hi sam
$ echo "hi||guy||sam" | awk -F'\\|\\|' '{print $1, $3}'
hi sam
Highlighted
Dennis Handly
Acclaimed Contributor

Re: How to set "||" as your field separator in awk

>and it output "aaa||bbb"

This won't happen on HP-UX's awk. My GNU awk will do that. HP-UX awk gives:
awk: There is a regular expression error.
Unknown error
The input line number is 1.
The source line number is 1.

As documented, FS is an Extended Regular Expression where "|" is special.
James R. Ferguson
Acclaimed Contributor

Re: How to set "||" as your field separator in awk

Hi:

Hence, the moral of this story is to escape characters with special meaning. The same applies if you used 'split':

# echo 'aaa||bbb'|awk '{split($0,a,/\|\|/);print a[1]}'
aaa

# echo 'aaa||||bbb'|awk '{split($0,a,/\|\|/);print a[1],a[3]}'
aaa bbb

...notice the four pipe symbols in the last example. We want to take them two-at-a-time as dictated by our regular expression. The second field is thus an empty one.

Regards!

...JRF...
Wang,MinJie
Super Advisor

Re: How to set "||" as your field separator in awk

Done Thank you guys!