0

I have string with "|" delimited fields:

name|phone|email|surname|house|street|

from code side, at the end of this string is "\n" How can I reorder this string using awk saving delimiter?

awk '{print $1,$4,$3,$2....}' doesn't work it just deletes column.

Jane
  • 17
  • 4
  • 2
    You should mention `awk -F'|' {print $1,$2,....}'` and it should fly then since your Input_file(shown sample) doesn't look like having space as delimiter so mention its delimiter as per your input and it should work then. – RavinderSingh13 Jun 27 '19 at 12:15
  • setting -F delimiter only replaces delimiter with space. Even tried using begin with FS – Jane Jun 27 '19 at 12:16
  • Do you just need to [swap a pair of fields](https://stackoverflow.com/questions/11967776/swap-two-columns-awk-sed-python-perl)? – Wiktor Stribiżew Jun 27 '19 at 12:17
  • 1
    You also need to set the output field separator `OFS`: `awk -v OFS="|" ...` or `awk 'BEGIN{FS=OFS="|"}` – James Brown Jun 27 '19 at 12:18
  • @Jane, if you give like `-F'|'` it should set delimiter like `|` for all lines of Input_file. – RavinderSingh13 Jun 27 '19 at 12:18
  • 1
    Please add your desired output (no description) for that sample input to your question (no comment). – Cyrus Jun 27 '19 at 12:24
  • Thanks, helped setting OFS, and don't know why, but setting -F '|' doesn't effect anything, but replacing... but -F'|' without space helped =\ – Jane Jun 27 '19 at 12:32

3 Answers3

1

Set input and ouput field separator:

echo 'name|phone|email|surname|house|street|' |\
  awk '{print $1,$4,$3,$2,$6,$7}' FS='|' OFS='|'

Output:

name|surname|email|phone|street|
Cyrus
  • 84,225
  • 14
  • 89
  • 153
1

Using awk

$awk '{print $1,$4,$3,$2}' FS="|" OFS="|" file
name|surname|email|phone
Jotne
  • 40,548
  • 12
  • 51
  • 55
0

Here is how to swap fields 2 and 4 via a temporary variable:

awk -F'|' '{ tmp=$2; $2=$4; $4=tmp } 1' OFS='|'
Thor
  • 45,082
  • 11
  • 119
  • 130