Replacing second column using shell script

2019-07-27 23:03发布

I want to change the second column to upper case and I want to do it in shell script only. (no one liners!)

#!/bin/sh
# read file line by line
file="/pdump/country.000000.txt"
while read line
do
mycol=`echo $line | awk -F"," '{print $2}'`
mycol_new=`echo $mycol | tr "[:lower:]" [:upper:]`
echo $line | awk -F"," '{print $1 "," $mycol_new "," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'
done < $file

I am not able to replace the $2 with $mycol_new. Any suggestion?

标签: sed awk grep shell
3条回答
Anthone
2楼-- · 2019-07-27 23:08

awk cannot see $mycol_new because it is a shell variable. Here is one way of passing a shell variable into awk using the -v flag:

echo $line | awk -v var="$mycol_new" -F"," '{print $1 "," var "," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'

Here is an alternative method which lets the shell expand $mycol_new:

echo $line | awk -F"," '{print $1 ",'"$mycol_new"'," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'
查看更多
Juvenile、少年°
3楼-- · 2019-07-27 23:29

why no one liners? Doing homework?

$ cat file
one two three four
five six seven eight

$ awk '{$2=toupper($2)}1' file
one TWO three four
five SIX seven eight
查看更多
Deceive 欺骗
4楼-- · 2019-07-27 23:29

If you want to do this all in the shell, then you don't need awk:

IFS=,
while read line; do
  set -- $line
  a="$1"
  b="${2^^}"  # assumes bash, use "tr" otherwise
  shift 2
  set -- "$a" "$b" "$@"
  echo "$*"
done < "$file" > "$file.new"
查看更多
登录 后发表回答