Home > Software engineering >  Replace a digit with another digit in bash
Replace a digit with another digit in bash

Time:03-30

I am writing a bash script in which I want to replace the first digit if 0 with 92 and if there is no 0 and 92 append 92 in front of that digit and save it in a new file.

Any help would be appreciated.

Below is my bash script:

scrap.sh

#!/bin/bash
file=test.txt
while IFS=, read -r field1
do
    echo $field1 | awk '$0*=1'>> test2.txt

done < $file

test.txt

03333333333
3848123249

expected output

923333333333
923848123249

CodePudding user response:

With your shown samples, please try following awk code.

awk '{$0=substr($0,1,1)==0?"92" substr($0,2):"92" $0} 1'  Input_file

Explanation: Simple explanation would be, using awk's substr function to get sub strings from current line. In main program of awk re-assigning values to current line($0) based on conditions. Checking condition if 1st character is 0 then make $0 value to 92 and rest of line from 2nd character ELSE add 92 before $0. Finally mentioning 1 will print current edited/non-edited line.

CodePudding user response:

With just bash parameter expansion:

$ while IFS= read -r line; do printf '92%s\n' "${line#0}"; done < test.txt
923333333333
923848123249

${line#0} removes a leading zero only if it exists.

https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion

CodePudding user response:

Assuming this is your input file:

cat file

03333333333
92123456789
3848123249

You can use this sed:

sed -E '/^92/!s/0|^/92/' file

923333333333
92123456789
923848123249

sed command details:

  • /^92/! do this for the lines that don't start with 92
  • /0|^/: Match first 0 or start position of a line
  • /92/: Replace with 92 at start position

An equivalent awk would be:

awk '!/^92/ {sub(/0|^/, "92")} 1' file

CodePudding user response:

I'd prefer a solution with a safety check :

  • (Confirmed working on gawk 5.11 mawk 1.3.4 mawk 1.9.9.6 macOS nawk)

      [nmg]awk '(/[1-9]/)*sub("^0?",92)'

Reason being, a solution such as awk '!/^92/ {sub(/0|^/, "92")} 1' mentioned above would result in extra empty rows as well as rows with only zeros getting the 92 (unless that's the desired effect))

i.e.

03333333333
3848123249

0

becomes

923333333333
923848123249
92
92

If you wanna trim out all leading zeros (instead of just 1 of them, and only want lines with non-zero numbers, and don't care for nawk at all, then it's simpler :

mawk2 '/[1-9]/*sub("^0*",92)'

or

mawk2 '(1<NF)*sub("^0*",92)' FS='[1-9]'
  • Related