Home > Mobile >  How to extract numbers of a string unix
How to extract numbers of a string unix

Time:01-03

Hello and happy new year. I have a question;i have a file named shipsIMO.txt in unix which contains the imo code of ships like:

IMO84855
IMO58484

How can I have as an output only the numbers using a bash script? Am I close?

echo "shipsIMO.txt"|tr -cd [:digit:]>single.txt

CodePudding user response:

How can I have as an output only the numbers

In that case, you are very close. echo "shipsIMO.txt" will not print the content of the file. It'll literally print shipsIMO.txt. To print the content of the file, use cat:

cat shipsIMO.txt | tr -cd '[:digit:]' > single.txt

or without cat, making tr read directly from the file:

tr -cd '[:digit:]' < shipsIMO.txt > single.txt

Both versions above would create single.txt with the content (no spaces or newlines):

8485584855

If you want to ...

# keep whitespaces (including newlines) and digits:
tr -cd '[:space:][:digit:]' < shipsIMO.txt > single.txt

# keep only newlines and digits:
tr -cd '\n[:digit:]' < shipsIMO.txt > single.txt

Both would produce single.txt with this content:

84855
84855

CodePudding user response:

You can do this easily with sed, removing all non-numeric characters:

sed -e 's/[^0-9]//g' shipsIMO.txt

CodePudding user response:

You can try with sed to remove all IMO string, it will work with space and line break:

sed 's/IMO//g'  shipsIMO.txt > single.txt
  • Related