Reputation: 55
I have a pipeline delimited file and I want to add a new word after field/ column 24 (indicated as filename in to be sample), i tried using
awk -F "|" '{{$(NF-2)="filename.txt"} print $0 }' OFS="|"
But this overwrites the adjacent columns.
as in:
0|ZZZZZ|Mr XXXXX|73 Up hill|Hurley|Atherstone|||XXX XXX|GB|00.01.2017|2134567686|7902379xxx|01.09.2017|25|||239|Stores Sheffield|||07.01.2018|13.10.2016||X||NP
to be:
0|ZZZZZ|Mr XXXXX|73 Up hill|Hurley|Atherstone|||XXX XXX|GB|00.01.2017|2134567686|7902379xxx|01.09.2017|25|||239|Stores Sheffield|||07.01.2018|13.10.2016||filename|X||NP
with awk:
0|ZZZZZ|Mr XXXXX|73 Up hill|Hurley|Atherstone|||XXX XXX|GB|00.01.2017|2134567686|7902379xxx|01.09.2017|25|||239|Stores Sheffield|||07.01.2018|13.10.2016||filename|||NP
can some help me with adding a word at particular position without overwriting.
Upvotes: 0
Views: 2134
Reputation: 26925
What about this, the idea is like thinking the files is a csv
but using |
as a delimiter:
awk -F"|" 'BEGIN { OFS = "|" } {$24="filename"}1' file
But this outputs:
...13.10.2016|filename|X||NP
Not with an extra |
like in your desired output example:
...13.10.2016||filename|X||NP
Could it be a typo?
In any case answer from @akshay-hegde is short and clean:
awk 'BEGIN{FS=OFS="|"}{$24=FILENAME}1' file
Upvotes: 0
Reputation: 19194
With sed with support for ERE ( -E
or -r
depending on your sed version):
sed -E 's/(([^|]*\|){24})/\1filename.txt|/'
Upvotes: 1
Reputation: 16997
I have a pipeline delimited file and I want to add a new word after character position 24 (indicated as filename in to be sample),
At char position 24, its will not give expected output, probably what you need is as follows, which will set 24th column in record with filename.txt,
0|ZZZZZ|Mr XXXXX|73 Up hill|Hurley|Atherstone|||XXX XXX|GB|00.01.2017|2134567686|7902379xxx|01.09.2017|25|||239|Stores Sheffield|||07.01.2018|13.10.2016||X||NP
^
|
This is 24th char position
since you have not posted without codetags, I assume, its one line, which contains total 27 fields, where separator being pipe (|
)
awk 'BEGIN{FS=OFS="|"}{$24="filename.txt"}1' file
If you want to have current filename at 24th field then, use FILENAME
awk 'BEGIN{FS=OFS="|"}{$24=FILENAME}1' file
NF-2
which gives 25, you still can correct your
code with NF-3
so that it will modify 24th fieldTo insert some string at char position 24, I prefer
sed
sed -r -e 's/^.{24}/&filename.txt/' filename
Upvotes: 0
Reputation: 12877
awk -F\| '{ for (i=1;i<=NF-2;i++) { printf "%s|",$i };printf "%s","filename";for (i=NF-1;i<=NF;i++) { printf "|%s",$x } }' filename
Print the all the | delimited fields up to X and print using a for loop. Print "filename" and then print the remaining fields.
Upvotes: 0