开发者

Replacing second column using shell script

开发者 https://www.devze.com 2023-02-17 04:49 出处:网络
I want to change the second column to upper case and I want to do it 开发者_JS百科in shell script only. (no one liners!)

I want to change the second column to upper case and I want to do it 开发者_JS百科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?


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}'


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


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消