0

I have following file:

./foldername/company_users_policies_changes.txt
"terraform_automated_python","AdministratorAccess"
./foldername/company_groups_policies.txt
"terraform_automated_python","ec2fullacess"
 ........................................

I want to leave only filenames not full path (remove everything except filename only)

Desired output:

 company_users_policies_changes
"terraform_automated_python","AdministratorAccess"
company_groups_policies
"terraform_automated_python","ec2fullacess"
 ........................................
Milister
  • 101
  • 2

2 Answers2

1

Your first line in the desired output contains a leading space but I assume that is simply a transcription error.

The following will find ./foldername/ at the beginning of line, and replace it with nothing, and similarly replace .txt at the end of a line with nothing.

sed -i 's%^\./foldername/%%;s/\.txt$//' filename

The -i option says to modify the file "in-place" (i.e. replace the original file with the edited file). On some platforms (notably *BSD, and thus also MacOS) you need an option -i '' which can be empty to say you don't want a backup file to be created (or give it something like -i ~ to save the original file as filename~).

It is not hard to combine the two actions into a single regex if you want to make sure they only occur when both conditions are true (though this complicates matters slightly in that you need to understand how to use a back reference);

sed -i 's%^\./foldername/\(.*\)\.txt$/\1/' filename

or you can add a conditional to the script to abandon the second action if the first does not succeed.

tripleee
  • 3,121
  • 5
  • 32
  • 35
-1
cat changes.txt | awk -F/ '{print $NF}' | sed -e 's/.txt\/$//' | sed -e 's/.txt//'

Output:

changes
 group_policies_changes
aaaaaaaaaa
 role_assignemnt_changes
"ec2ssmMaintWindow","AmazonSSMMaintenanceWindowRole","ssm.amazonaws.com--ec2.amazonaws.com"
"ec2ssmRole","AmazonEC2RoleforSSM--AmazonSSMFullAccess","ssm.amazonaws.com--ec2.amazonaws.com"
 users_policies_changes
"terraform_automated_python","AdministratorAccess"
Milister
  • 101
  • 2
  • 2
    You have a [useless use of `cat`](https://superuser.com/questions/323060/what-is-the-general-consensus-on-useless-use-of-cat) and the [two `sed` commands can easily be combined](https://superuser.com/questions/620523/merge-two-separate-sed-expressions-into-one). The Awk can also easily be factored out; remember that Awk is strictly a superset of `sed`, but here, you can also refactor the replacement to be part of the `sed` script. – tripleee Mar 26 '18 at 10:05
  • Thanks @tripleee but i'm just beginner in this, don't think i deserve downvote – Milister Mar 26 '18 at 10:34