简体   繁体   中英

How can i use awk to ignore a comma?

How can I separate a comma using awk for the below

1, servername, url, Properties, hostname, version, os, application server.

I have saved the above line in a file called test.properties and using the following command

awk  '{ print $1 }' test.properties

and i just want the server name to be printed in the output, instead, it prints the whole line.

Should i use cut instead for situations like this?

Given:

$ echo "$txt"
1, servername, url, Properties, hostname, version, os, application server

Just set the field separator properly to a comma:

$ echo "$txt" | awk -F, '{print $1}'    
1

Or, as you say, use cut :

$ echo "$txt" | cut -d , -f1    
1

是的,您应该在这种情况下使用cut,这是它设计的目的。

You could also use bash built-ins if your string only contains characters from ASCII 0x20-0x7f except backslash (\\) 0x5c (Note the caveats mentioned by Stéphane Chazelas about dealing with shell variables):

s='1, servername, url, Properties, hostname, version, os, application server'
IFS=', ' read _ server _ <<<"$s"
echo "'$server'"

Output:

'servername'

Or by using positional parameters:

oIFS="$IFS"
export IFS=', '
set -- $s
echo $2
IFS="$oIFS"

Or:

function getserver() (
  export IFS=', '; set -- $1; echo $2
)
getserver "1, servername, url, Properties, hostname, version, os, application server"

Output:

servername

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM