I have a list of strings that are always 5 characters long. What is the best way to transform the first, third and fifth character (including space) of each line into individual strings?
Input:
c c
8 8
4 4
3 3
1 1
4 4
9 9
8 | c
> 4
0 0
e | 5
6 | a
3 3
9 | c
b <
1 1
b | 0
d <
4 4
5 | 7
c c
> 3
. .
1 | c
o o
Output:
c8431498 0e639b1bd45c .1o
c843149c405a3c 10 47c3.co
|> || |< | | > |
I had some success with using sed capture group but it ignores the trailing spaces.
sed -e "s/^.*\(.\)$/\1/"
Edit: Clarified that I need space included as well and string includes a dot
using GNU awk:
awk 'BEGIN{FS="";a="";b="";c="";}{a=a$1; b=b$3; c=c$5;}END{print a ORS c ORS b}' filename
output:
c8431498 0e639b1bd45c
c843149c405a3c 10 47c3
|> || |< |< | >
Here is one using GNU awk and empty FS
:
$ awk -F "" '{for(i=1;i<=5;i++)a[i]=a[i] ($i==""?" ":$i)}END{print a[1] ORS a[5] ORS a[3]}' file
c8431498 0e639b1bd45c
c843149c405a3c 10 47c3
|> || |< |< | >
Another nice awk
solution using FIELDWITHS
awk internal variable:
FIELDWIDTHS A whitespace separated list of field widths. When set, gawk parses the input into fields of fixed width, instead of using the value of the FS variable as the field separa- tor. See Fields, above.
Example:
$ awk -v FIELDWIDTHS="1 1 1 1 1" '{b1=b1$1;b3=b3$3;b5=b5$5}END{print b1;print b5;print b3}' to_horizontal.txt
c8431498 0e639b1bd45c
c843149c405a3c 10 47c3
|> || |< |< | >
you can use FIELDWIDTHS
instead of the classic FS
in order to defined fixed size columns that will be after manipulated and accessed as usual by using $1
, $2
, $3
, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With