honj - t
honj - t

Reputation: 107

How to delete multiple same characters from a file using bash script?

I have this script which removes the first periods from a file in order to unhide it. However, all it can do is remove the first period and not the succeeding periods, which makes the file still hidden. What I want to know now is how I can remove more than 1 periods at a time to unhide the file.

#!/bin/bash
period='.'
for i in $@; do
      if [[ "$i" == "$period"* ]] ; then
            mv "$i" "${i#"$period"}"
      else
            mv $i .${i}
      fi
 done

I have some knowledge in using grep and regex so I thought of using + to remove a lot of them at a time but I cant really figure out if it is the correct way to go about it

Upvotes: 0

Views: 157

Answers (1)

Shawn
Shawn

Reputation: 52439

You can use the bash extended glob +(pattern) to match one or more periods, combined with the ## parameter expansion to remove the longest leading match:

#!/usr/bin/env bash

# Turn on extended globs
shopt -s extglob

name=...foo
printf "%s -> %s\n" "$name" "${name##+(.)}"

Or you can use a regular expression, combining looking for leading periods with capturing the rest of the name:

#!/usr/bin/env bash

# Note the quoted parameters to avoid many issues.
for i in "$@"; do
      if [[ "$i" =~ ^\.+(.*) ]]; then
            mv "$i" "${BASH_REMATCH[1]}"
      else
            mv "$i" ".${i}"
      fi
 done

Upvotes: 4

Related Questions