Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed print Nth character

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

like image 907
user3534227 Avatar asked Jan 29 '18 07:01

user3534227


3 Answers

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
       |> || |< |< | >
like image 138
tso Avatar answered Nov 20 '22 13:11

tso


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
       |> || |< |< | >
like image 25
James Brown Avatar answered Nov 20 '22 13:11

James Brown


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, ...

like image 4
Allan Avatar answered Nov 20 '22 14:11

Allan