19

I'd like to add characters to the end of every line of text in a .txt document.

#Define Variables
$a = c:\foobar.txt
$b = get-content $a

#Define Functions
function append-text  
    {  
    foreach-Object  
        {  
        add "*"  
        }  
    }  

#Process Code
$b | append-text

Something like that. Essentially, load a given text file, add a "*" the the end of every single line of text in that text file, save and close.

Joshua
  • 397
  • 1
  • 5
  • 7

4 Answers4

28

No function necessary. This would do it:

$b|foreach {$_ +  "*"}
Ed Schwehm
  • 2,163
  • 4
  • 32
  • 55
Elroy Flynn
  • 3,032
  • 1
  • 24
  • 33
  • 4
    And if you're wrists are bothering you `gc c:\foobar.txt | %{"$_*"}`. That is using aliases heavily but I tend to use PowerShell for a lot of one-offs at the command line and the less I have to type the more my wrists don't hate me. :-) – Keith Hill Feb 10 '11 at 03:52
  • This definitely works, but I was hoping to keep it in function format so that I could call it again if necessary. You're probably right though, my goal on this script probably makes the need for a function unnecessary. – Joshua Feb 10 '11 at 04:12
4

Soemthing like this should work:

function append-text { 
  process{
   foreach-object {$_ + "*"}
    } 
  }
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • 3
    If you use a filter, you don't need the `process` block at all e.g. `filter Append-Text {"$_*"}` – Keith Hill Feb 10 '11 at 03:49
  • This works great! Is it possible add a redundancy check into this? Something that would check for the presence of "*", and if it is not at the end of a line, then add it? – Joshua Feb 10 '11 at 04:10
  • 2
    Sure, `filter Append-Text {if ($_ -match '\*\s*$') {$_} else {"$_*"}}` – Keith Hill Feb 10 '11 at 04:30
  • Sometimes people are just looking for an example of how to do something, and present a simple example to use that's easier to solve by some other method but giving them that doesn't really answer the question they were asking. Other times the giving them the alternate method is the "right" answer. Sometimes I guess wrong. – mjolinor Feb 10 '11 at 04:52
  • I think Keith's regex above '*\s*$' is not correct. In any case instead of -match I would use -like, i.e. "$_ -notlike '*`*' – Elroy Flynn Feb 10 '11 at 14:18
  • Well the first asterisk *was* escaped when I wrote it. Seems that SO comments is swallowing it up. Let me try double escaping - `'\\*\s*$'` .... And that works much better. – Keith Hill Feb 10 '11 at 15:40
4
PS> (gc c:\foobar.txt) -replace '\S+$','$&*'
walid2mi
  • 2,704
  • 15
  • 15
0

Simply took about 2 hours to work it out, had never used Powershell before, but here you go:

cls
#Define Functions
(gc g:\foobar.txt) -replace '\S+$','$& 1GB RAM 1x 1 GB Stick' | out-file "g:\ram 6400s.txt"

Change the file location. First file is the file you want to edit. The secound one is the output file.

Taryn
  • 242,637
  • 56
  • 362
  • 405