Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
Replace a digit with another digit in bash

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
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!