我的行和列前面都有我不需要的介绍。列没有标题。我当前文件中的数据看起来像这样(IP地址是假的(:
This is a totally extraneous introduction and does not have anything to do with the data. It is here as a facsimile of what the output file looks like.
df bank.com 10.10.10.1
sdfdg store.com 10.10.10.2
s church.com 10.10.10.3
我需要跳过介绍,粘贴提取的数据如下所示(源自上面的第二字段(,并将其全部放入一个新的.txt
文件中。字符串不需要引号:
bank.com,store.com,church.com
关于如何在Bash中做到这一点,有什么建议吗?
我试着使用下面的技巧,但它只抓住了引言的第一行,并没有贯穿每一行。
将多行字符串转换为单逗号分隔
假设:
- 总是跳过输入文件的前2行
- 第二个字段不包含空白
- 没有空行
样本数据文件:
$ cat input.dat
This is a totally extraneous introduction and does not have anything to do with the data. It is here as a facsimile of what the output file looks like.
df bank.com 10.10.10.1
sdfdg store.com 10.10.10.2
s church.com 10.10.10.
一个awk
解决方案:
$ awk 'FNR>2 {printf "%s%s", pfx, $2; pfx=","} END {printf "n"}' input.dat
bank.com,store.com,church.com
说明:
FNR>2
-对于大于2的记录(行(编号printf "%s%s", pfx, $2
-打印我们的前缀(最初为空(加上字段#2;因为格式中没有n
,所以光标留在当前行上pfx=","
-将文件其余部分的前缀设置为逗号(,
(END {printf "n"}
-将n
添加到行的末尾
这应该有效:
tail -n +3 filename | awk '{print $2}' | sed -z 's/n/,/g;s/,$/n/' > newfile.txt
tail -n +3
将跳过文件的前2行(因此将其更改为介绍的行数加一(。
下一部分只打印出你感兴趣的第二列
第三个用逗号替换换行符。
最后一部分将输出放入一个新文件中。