Reputation: 41
I want to copy all the text in a text file and to add at the beginning of each line in another text file.
I have tried with sed, I can put a char at the beginning of each line but I don't how to copy text from another file
I have tried this:
sed 's/^/#/' 2.txt > 3.txt
but this puts only a char or a string.
Example:
I have in the 2.txt the words:
u
ubbia
ubbidiente
ubbidienza
ubbidire
ubertoso
in the second 3.txt I have the same lines but with explanation:
u = explanation here
ubbia = explanation here
ubbidiente = explanation here
ubbidienza = explanation here
ubbidire = explanation here
ubertoso = explanation here
I want this result:
u u = explanation here
ubbia ubbia = explanation here
ubbidiente ubbidiente = explanation here
ubbidienza ubbidienza = explanation here
ubbidire ubbidire = explanation here
ubertoso ubertoso = explanation here
Upvotes: 2
Views: 300
Reputation: 58473
This might work for you (GNU sed):
sed -E 's/.*/printf "%-15s" &/e;s#(\S+).*#s/^\\<\1\\>/&\1/#' file1 |
sed -f - -e 't;d' file2
This builds a sed script from file1 and runs it against file2. If a line from file1 matches the first word for file2, the printf formatted line from file 1 is prepended to the matching line from file2, otherwise it is deleted. If you prefer to leave unmatching lines from file2 alone, remove the -e 't;d'
commands from the above solution.
N.B. This solution does not require either file to be sorted, however for large files it may be time intensive.
From your comments to jas, if the file is 1-1, this may work for you:
parallel -k 'printf "%-15s%s\n" {1} {2}' ::::+ file1 file2
Upvotes: 0
Reputation: 10865
Why do you need the first file at all? Why not just:
$ awk '{print $1 "\t" $0}' 3.txt | column -t -s $'\t'
u u = explanation here
ubbia ubbia = explanation here
ubbidiente ubbidiente = explanation here
ubbidienza ubbidienza = explanation here
ubbidire ubbidire = explanation here
ubertoso ubertoso = explanation here
Upvotes: 0
Reputation: 133600
Could you please try following, this solution will make indentation in output as per length of maximum length of 1st column(a logic has been written for it), tested with given samples.
awk '
FNR==NR{
a[FNR]=$1
c[$1]
next
}
($1 in c){
b[++count]=$0
len=len>length($1)?len:length($1)
}
END{
for(i=1;i<=count;i++){
val=len<length(b[i])?len+(len-length(a[i])):len
printf("%s%"val"s%s\n",a[i],OFS,b[i])
}
}
' 2.txt 3.txt
Output will be as follows.
u u = explanation here
ubbia ubbia = explanation here
ubbidiente ubbidiente = explanation here
ubbidienza ubbidienza = explanation here
ubbidire ubbidire = explanation here
ubertoso ubertoso = explanation here
Upvotes: 1