Modifying text using awk

awk, linux, replace, sed, text

Solution

Set the field separator as `=` and print the second field:

# With awk                                                                     
$ awk -F= '{print $2}' file
chr1      20802865        20802871        
chr1      23866528        23866534

# Or with cut
$ cut -d= -f2 file                  
chr1      20802865        20802871        
chr1      23866528        23866534

# How about grep
$ grep -Po '(?<==).*' file
chr1      20802865        20802871        
chr1      23866528        23866534

# Temp file needed
$ cut -d= -f2 file > tmp; mv tmp file

Both `awk`, `cut` and `grep` require temporary files if you want to store the changes back into `file`, a better solution would be to use `sed`:

 sed -i 's/range=//' file

This substitutes `range=` with nothing and the `-i` means the changes are done in-place so no need to handle the temporary files stuff as `sed` does it for you.

Problem

I am trying to modify text files using awk. There are three columns and I want to delete part of the text in the first column: ``` range=chr1 20802865 20802871 range=chr1 23866528 23866534 ``` to ``` chr1 20802865 20802871 chr1 23866528 23866534 ``` How can I do this? I've tried `awk '{ substr("range=chr*", 7) }'` and `awk '{sub(/[^[:space:]]*\\/, "")}1'` but it deletes all the contents of the file.

Original source