1

I'm trying to simplify my life here but I'm stuck. I have a file containing multiple lines. Each line has a user and a number. I'd like to know a bash one-liner to search for a user and change the number. How could this be done? Thanks in advance.

My files are structured like this:

crmopr 162756
tpiopr 102334
ddnope 210928

--SOLVED--

This one-liner does the jobs.

sed -i '/MATCHING_STRING/s/MATCHING_NUMBER/NEW_NUMBER/1' file

MATCHING_STRING: the string for finding the line i want to the change the number

MATCHING_NUMBER: the number that's going to be substituted

NEW_NUMBER: the new number

/1: change only first sustitution match in line (could be /g in this case too)

-i: makes changes permanent

--EDIT--

Accepted solution which came seconds after I edited the OP also worked!

migrated from serverfault.com Aug 31 '15 at 20:58

This question came from our site for system and network administrators.

  • You need to provide (1) An example of what the data looks like (2) What your script/command looks like so far (3) What you've tried that doesn't work. All of these things are necessary to help you since we don't (A) know exactly what you need and (B) we need you to show you've put effort into solving this problem and you're not just asking us to do your job for you. – Gene Aug 24 '15 at 7:49
  • Ok, sorry for that, yes, it seems that I'd like people over here to do my work, which is not the case. After searching more I found a solution. I'll edit now the OP. Thanks Gene. – Luis Garnica Guilarte Aug 24 '15 at 8:09
  • You shouldn't edit the question to include a solution. Write a real answer instead. – kasperd Aug 24 '15 at 9:56
  • failed if pattern is a subpattern of other entry, add ^and $ arround your matching pattern – NeronLeVelu Sep 4 '15 at 6:58
2

If your file looks like:

abcd 1234
djhd 6534
fytf 4544

You could execute a AWK one-liner like this

index=2;for i in `cat filename`; do echo $i; done|awk -v OFS=" " -v \
INDEX=$index '$1 ~ /^abcd$/ {$2="1233"; print }' >> NewFile.txt

This will match the name dddd and replace the 1234 with 1233. This will redirect the output result to new file called NewFile.txt.

So your NewFile will have the replaced entries. This can be programmed to iterate through all the File entries.

  • Yes, it helped! I tried too and it worked, since it's very different from my aproach, I'll take a time to study it. Thanks mate! – Luis Garnica Guilarte Aug 24 '15 at 8:24
1

simple awk (but sed is better in this case)

awk '$1 ~ /^MatchingString$/ {$2 = NEW_NUMBER}1' YourFile > NewFile
  • limit to EXACT pattern matching (avoid sub pattern false selection)

for a more generic (using bash variable content)

awk -v "User=${UserWanted}" -v "Data=${WantedNumber}" '$1 == User { $2 = Data} 1' YourFile > NewFile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.