使用sed / awk或任何Linux命令单行,如何在不使用Perl /其他工具的情况下更改以下行。
从
1:is is is is is is
2:is is
3:is
4:is
以
is:1,1,1,1,1,1
is:2,2
is:3
is:4
答案 0 :(得分:1)
这是一种快速而又肮脏的方式:
awk '
BEGIN { FS = OFS = ":" }
{
sep = "";
n = split ($2, t, / /);
$2 = "";
for (i=1; i<=n; i++) {
$2 = $2 sep $1;
sep=","
}
$1 = t[1]
}1' file
is:1,1,1,1,1,1
is:2,2
is:3
is:4
答案 1 :(得分:1)
看看你以前的帖子,我认为这是你真正想要的:
$ cat file
This is a file, my name is Karl, what is this process, karl is karl junior, file is a test file, file's name is file.txt
My name is not Karl, my name is Karl Joey
What is your name?
Do you know your name and what it is?
$ awk -v tgt="is" '
BEGIN { FS = "(^|[^[:alpha:]])" tgt "([^[:alpha:]]|$)" }
NF>1 {
printf "%s:", tgt
for (i=2; i<=NF; i++)
printf "%s%s", NR, (i<NF?",":ORS)
}' file
is:1,1,1,1,1,1
is:2,2
is:3
is:4
如果你有GNU awk,你可以使用\\<
和\\>
代替(^|[^[:alpha:]])
和([^[:alpha:]]|$)
。
您应该在示例输入中添加一行Is
(大小写混合)以及预期输出,以向我们显示您的脚本是否应该区分大小写。以上是区分大小写的,如果不是你想要的,请改为:
$ awk -v tgt="is" '
BEGIN { FS = "(^|[^[:alpha:]])" tolower(tgt) "([^[:alpha:]]|$)" }
{ $0 = tolower($0) }
NF>1 {
printf "%s:", tgt
for (i=2; i<=NF; i++)
printf "%s%s", NR, (i<NF?",":ORS)
}' file
请注意,这只是@jaypal给你上一个问题https://stackoverflow.com/a/25336554/1745001的gawk特定答案的变体。
答案 2 :(得分:1)
这个单行怎么样:
awk -F':' -v OFS=":" '{t=$1;split($2,a," ");$1=a[1];gsub(/[^ ]+/,t,$2)}7' file
awk -F':' -v OFS=":" '{t=$1;split($2,a," ");$1=a[1];
gsub(/[^ ]+ /,t",",$2);sub(/[^,]*$/,t,$2)}7' file
答案 3 :(得分:0)
这应该做:
awk -F":| " '{printf "%s,",$2;for(i=2;i<NF;i++) printf "%s,",$1;print $1}' file
is,1,1,1,1,1,1
is,2,2
is,3
is,4