Reputation: 1893
Using sed / awk or any Linux commands one-liner, how can i change the following lines without using Perl/other tools.
from
1:is is is is is is
2:is is
3:is
4:is
to
is:1,1,1,1,1,1
is:2,2
is:3
is:4
Upvotes: 0
Views: 63
Reputation: 203169
Looking at your previous posts, I THINK this is what you're really looking for:
$ 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
If you have GNU awk you can use \\<
and \\>
instead of (^|[^[:alpha:]])
and ([^[:alpha:]]|$)
.
You should have included a line with Is
in it (mixed case) in your sample input and expected output to show us whether or not your script should be case-sensitve. The above IS case sensitive, if that's not what you want change it to:
$ 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
Note that is is just variations of the gawk-specific answer @jaypal gave to your previous question, https://stackoverflow.com/a/25336554/1745001.
Upvotes: 1
Reputation: 41446
This should do:
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
Upvotes: 0
Reputation: 195029
How about this one-liner:
awk -F':' -v OFS=":" '{t=$1;split($2,a," ");$1=a[1];gsub(/[^ ]+/,t,$2)}7' file
oh, I didn't notice that you want the comma to separate the fields:
awk -F':' -v OFS=":" '{t=$1;split($2,a," ");$1=a[1];
gsub(/[^ ]+ /,t",",$2);sub(/[^,]*$/,t,$2)}7' file
Upvotes: 1
Reputation: 77065
Here is a quick and dirty way:
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
Upvotes: 1