简体   繁体   中英

How To replace leading zero with spaces in linux?

i have text like this

Jan 28\|Jan 29\|Jan 30\|Jan 31\|Feb 01\|Feb 02\|Feb 03\|Feb 04

i want to the result like this

Jan 28\|Jan 29\|Jan 30\|Jan 31\|Feb  1\|Feb  2\|Feb  3\|Feb  4

i have been searching all over and get no result, please help

With gawk you can use gensub :

awk '{print gensub(/ 0([0-9])/,"  \\1", "g")}' file
Jan 28\|Jan 29\|Jan 30\|Jan 31\|Feb  1\|Feb  2\|Feb  3\|Feb  4

Or same pattern with sed :

sed  's/ 0\([0-9]\)/  \1/g' file
Jan 28\|Jan 29\|Jan 30\|Jan 31\|Feb  1\|Feb  2\|Feb  3\|Feb  4

A minimal pattern to simply replace space followed by 0 with two spaces(because 2 digits days won't have a leading 0 ):

sed 's/ 0/  /g' file

Add the -i flag to edit the file in place:

sed -i 's/ 0/  /g' file

If you want to be more restrictive, with backreference you can search and replace months followed by one space and 0 with month and space without the 0 :

sed 's/\(|[A-Za-z]\{3\} \)0/\1 /g'
echo "Jan 28\|Jan 29\|Jan 30\|Jan 31\|Feb 01\|Feb 02\|Feb 03\|Feb 04"|\
> awk '{gsub(/ 0/,"  ")}1'

Jan 28\|Jan 29\|Jan 30\|Jan 31\|Feb  1\|Feb  2\|Feb  3\|Feb  4

This might work for you (GNU sed):

sed 's/\b[0-9]\b/0&/g' file

Prefix a singleton digit with a zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM