使用shell脚本替换第二列

时间:2011-03-17 11:14:13

标签: sed awk grep shell

我想将第二列更改为大写,我想仅在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。 有什么建议吗?

3 个答案:

答案 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"