gpt4 book ai didi

awk - 如何用 CLI 上某些行的逗号替换\n

转载 作者:行者123 更新时间:2023-12-04 00:51:12 25 4
gpt4 key购买 nike

我有以下文本文件。

 # This is a test 1
"watch"
"autoconf"

# This is another line 2
"coreutils"
"binutils"
"screen"

# This is another line 3
"bash"
"emacs"
"nano"
"bison"

# This is another line 4
"libressl"
"python"
"rsync"
"unzip"
"vim"

我想将其更改为以下内容:

# This is a test 1
watch, autoconf

# This is another line 2
coreutils, binutils, screen

# This is another line 3
bash, emacs, nano, bison

# This is another line 4
libressl, python, rsync, unzip, vim

删除前导空格,删除引号,用逗号替换新行。

到目前为止我得到了这个:

$ cat in.txt | sed 's/"//g' | sed 's/^[[:space:]]*//'> out.txt
# This is a test 1
watch
autoconf

# This is another line 2
coreutils
binutils
screen

# This is another line 3
bash
emacs
nano
bison
...

我不确定如何用逗号替换新行。我尝试了以下方法。

# no change
$ cat in.txt | sed 's/"//g' | sed 's/^[[:space:]]*//'| sed 's/\n/,/g'> out.txt

# changed all new lines
$ cat in.txt | sed 's/"//g' | sed 's/^[[:space:]]*//'| sed -z 's/\n/,/g'> out.txt
$ cat out.txt
# This is a test 1,watch,autoconf,,# This is another line 2,coreutils,binutils,screen,,# This is another line 3,bash,emacs,nano,bison,,# This is another line 4,libressl,python,rsync,unzip,vim

我怎样才能做到这一点?

最佳答案

这可能对你有用(GNU sed):

sed -E 's/^\s*//;/^"(\S*)"/{s//\1/;H;$!d};x;s/.//;s/\n/, /gp;$d;z;x' file

去除所有行前面的空白。

去掉双引号并将这些词附加到保留空间。

否则,切换到保留空间,删除第一个引入的换行符,用 , 替换所有其他换行符,打印结果,然后切换回模式空间并打印。

关于awk - 如何用 CLI 上某些行的逗号替换\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66415497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com