How to Remove All Non-Numeric Characters from a String in Bash

How do I remove non numeric characters from only one column of a .csv file in bash?

Now that we know the actual input is comma delimited, here's the quickest solution to your question.

sed -i 's/^[^0-9]\+//;s/[^0-9,]\+//' largefile.csv

s/^[^0-9]\+// - will remove any non-numeric from the start of the line.

s/[^0-9,]\+// - will remove any non-numeric trailing the numbers just before the comma.

How to remove all non-numeric characters from filename recursively

Here's you code adjusted to work recursively:

topdir=~/"Desktop/pictures/in_one_folder"
find "$topdir" -type f -iname '*.jpg' -print0 |
while IFS= read -r -d '' path; do
dir="${path%/*}"
file="${path##*/}"
remove_non_numeric=$(echo "$file" | sed 's/[^0-9]*//g')
add_extension="$remove_non_numeric.jpg"
echo "$dir/$add_extension"
mv "$path" "$dir/$add_extension"
done

It uses find to locate all files and then it process them one by one in a while loop.

One way to make this slightly faster is by avoid using sed. You can delete the non numeric characters with pure bash as follows:

        remove_non_numeric="${file//[^0-9]/}"

Replace all non alpha-numeric characters with dots using bash commands

The following works:

echo "test/my-1st$@#@-t_-/ \_est" | sed -e "s/\W/./g" | sed -e "s/_/./g" | tr -s .
  1. Replace non word characters (non a-zA-Z_) with dot (.)
  2. Replace underscores (_) with dot (.)
  3. Squash sequences of dots into a single dot

Online test: https://rextester.com/GJOW76941

A shorter option:

echo "test/my-1st$@#@-t_-/ \_est" | sed -e "s/\W/_/g" | tr -s _ .
  1. Replace non word characters (non a-zA-Z_) with underscore (_)
  2. Squash and replace underscores (_) with dot (.)

Bash - Remove all text after characters using wildcards

You can round a float with printf. Try printf "%.2f" "${NUMBER}". You could save the value into a variable as well: printf -v myvar "%.2f" "${NUMBER}".

Replace all non-alphanumeric characters in a string with an underscore

sed approach:

s="The/Sun is red@ .//hack Moon"

sed -E 's/[^[:alnum:][:space:]]+/_/g' <<<"$s"
The_Sun is red_ _hack Moon

  • [^[:alnum:][:space:]]+ - match any character sequence except alphanumeric and whitespace

Removing non-alphanumeric characters with sed

tr's -c (complement) flag may be an option

echo "Â10.41.89.50-._ " | tr -cd '[:alnum:]._-'


Related Topics



Leave a reply



Submit