如何解决如何从列表中的行中提取第二个元素,并使用 BASH 将元素以逗号分隔的行存储在新文件中?
我的行和列前面有一个我不需要的介绍。列没有标题。我当前文件中的数据看起来像这样(IP 地址是假的):
.txt
我需要跳过介绍,将提取的数据粘贴到如下所示(源自上面的字段 2),并将其全部放入一个新的 bank.com,store.com,church.com
文件中。字符串不需要引号:
export const CheckBoxChecked = Template.bind({});
CheckBoxChecked.args = {
label: 'Checked',checked: true,};
有关如何在 Bash 中执行此操作的任何建议?
我尝试使用以下技术,但它只抓取了介绍的第一行,并没有遍历每一行。
Turning multi-line string into single comma-separated
解决方法
假设:
- 总是跳过输入文件的前两行
- 第二个字段不包含空格
- 没有空行
示例数据文件:
wchar_t c = '\x720';
一个$ 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
- 记录(行)数大于 2 ... -
FNR>2
- 打印我们的前缀(最初为空白)加上字段 #2;因为光标留在当前行的格式中没有printf "%s%s",$2
-
\n
- 为文件的其余部分设置前缀为逗号 (pfx=","
) -
,
- 在行尾添加END {printf "\n"}
这应该有效:
tail -n +3 filename | awk '{print $2}' | sed -z 's/\n/,/g;s/,$/\n/' > newfile.txt
tail -n +3
将跳过文件的前 2 行(因此将其更改为介绍的行数,加上一行)。
下一部分只打印出您感兴趣的第二列。
第三个用逗号替换换行符。
最后一部分将输出放入一个新文件中。