我想将第二列更改为大写,我想仅在shell脚本中执行此操作。 (没有人衬里!)
#!/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
我无法用$ mycol_new替换$ 2。 有什么建议吗?
答案 0 :(得分:4)
awk
无法看到$mycol_new
,因为它是一个shell变量。这是使用-v
标志将shell变量传递给awk的一种方法:
echo $line | awk -v var="$mycol_new" -F"," '{print $1 "," var "," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'
以下是另一种让shell展开$mycol_new
的方法:
echo $line | awk -F"," '{print $1 ",'"$mycol_new"'," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'
答案 1 :(得分:2)
为什么没有一个衬垫?做作业?
$ cat file
one two three four
five six seven eight
$ awk '{$2=toupper($2)}1' file
one TWO three four
five SIX seven eight
答案 2 :(得分:0)
如果你想在shell中完成所有这些,那么你不需要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"