Bash脚本:在excel中剪切下一行并通过命令行粘贴到新列中



我有一个csv文件,我在shell脚本中使用,其中我的数据如下

ColumnName1
NameOfAnObject1
100
NameOfAnObject2
200

我的要求是获取数据并以以下格式存储在csv文件中

ColumnName1         ColumnName2
NameOfAnObject1     100
NameOfAnObject2     200

我已经试着用下面的命令获取数据awk '{getline nextLine; print nextLine,$1}' OFS="," file.csv

但是我得到的输出是
ColumnName1
NameOfAnObject1,100
NameOfAnObject2,200

这可能是你想要做的:

$ awk -v OFS='t' 'NR==1{p=$1; sub(/1$/,2,$1)} NR%2{print p, $1} {p=$1}' file
ColumnName1     ColumnName2
NameOfAnObject1 100
NameOfAnObject2 200

如果你曾经考虑过使用getline,那么请阅读http://awk.freeshell.org/AllAboutGetline来理解为什么你可能不应该,就像在这种情况下。

上面的脚本只是在第一个列标题的末尾用2替换1,所以它只会重现列名的开头部分,而不是硬编码我们认为它应该是什么。

使用sed

$ sed '1s/([^0-9]*).*/&t12/;1!{/^[A-Z]/{N;s/n/t/g}}' input_file
ColumnName1     ColumnName2
NameOfAnObject1 100
NameOfAnObject2 200

如果您的数据总是按照描述的格式格式化,则可以这样做:

(为了清晰,使用换行格式)。

awk '
BEGIN {              # print headers and set separator
OFS="t"; 
print "ColumnName1", "ColumnName2"
} 
NR>1{                # skip first line which is header
getline N;         # read first col, this continues to next line
print $0, N;       # print the line and data from line before
N=""}              # ..do not keep the previous line anymore
'  file.csv
ColumnName1             ColumnName2
NameOfAnObject1         100
NameOfAnObject2         200

最后一次设置N="是为了避免在文件末尾有一个N的剩余输出(如果你的文件以换行符结束)

如果您的输入是file.sample,如下所示:

ColumnName1
NameOfAnObject1
100
NameOfAnObject2
200

,那么你可以尝试one-linersed:

sed -i '2i ColumnName2' file.sample && cat file.sample | sed 'N;s/n/t/g' > file.csv

如果你catfile.csv,你应该得到:

ColumnName1     ColumnName2
NameOfAnObject1 100
NameOfAnObject2 200

awk正确地将t解释为字段分隔符,如果您这样做:

awk -F"t" '{ print $1 }' file.csv

输出:

ColumnName1
NameOfAnObject1
NameOfAnObject2

最新更新